package udpPackage;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.*;

import tcpPackage.serverBoard;

//import tcpServer.OnMessageReceived;

import java.io.*;

/**
 * @author Trevorr
 *
 */
public class udpServer extends Thread
{

	public static final int SERVERPORT = 4444;
    private boolean running = false;
    private OnMessageReceived messageListener;
    
    private DatagramSocket serverSocket;
	private byte[] receiveData = new byte[1024];
	private byte[] sendData = new byte[1024];
	private InetAddress IPAddress;
    private int clientPort;

    public static void main(String[] args) {
    	 
        //opens the window where the messages will be received and sent
        serverBoard frame = new serverBoard();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
 
    }
 
    /**
     * Constructor of the class
     * @param messageListener listens for the messages
     */
    public udpServer(OnMessageReceived messageListener) {
        this.messageListener = messageListener;
    }
 
 
    /**
     * Method to send the messages from server to client
     * @param message the message sent by the server
     */
    public void sendMessage(String message){
        /*if (mOut != null && !mOut.checkError())
        {
            mOut.println(message);
            mOut.flush();
        }*/
    	if (IPAddress != null)
        {
	    	sendData = message.getBytes();
	    	DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, clientPort);
		    try {
				serverSocket.send(sendPacket);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("Exception occured when sending packed over datagram packet.");
				e.printStackTrace();
			}
        }
    }
 
    @Override
    public void run() {
        super.run();
 
        running = true;
 
        try
        {
            System.out.println("S: Connecting...");
            //create a datagram socket
            serverSocket = new DatagramSocket(SERVERPORT);
            
            //create a DatagramPacket to receive a packet from client
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            
            //create connection and register clients ipaddress and port number
            serverSocket.receive(receivePacket);
            System.out.println("S: Receiving...");
            IPAddress = receivePacket.getAddress();
            clientPort = receivePacket.getPort();
            
            try
            {
                //in this while we wait to receive messages from client (it's an infinite loop)
                //this while it's like a listener for messages
                while (running) {
                	String message = new String( receivePacket.getData());
 
                    if (message != null && messageListener != null) {
                        //call the method messageReceived from ServerBoard class
                        messageListener.messageReceived(message);
                    }
                }
 
            } catch (Exception e) {
                System.out.println("S: Error");
                e.printStackTrace();
            } finally {
                serverSocket.close();
                System.out.println("S: Done.");
            }
 
        } catch (Exception e) {
            System.out.println("S: Error");
            e.printStackTrace();
        }
 
    }
 
 
    //Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard
    //class at on startServer button click
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
 
}